package com.demo;

import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * <code>ListToTree</code>
 * </p>
 *
 * @author junbao3
 * 集合转树
 * @date 2023-03-28 10:23
 */
public class ListToTree {
    private static List<Node> resultFromDb;
    static{
        //模拟结果集从数据库查询得到
        resultFromDb = new ArrayList<>();
        resultFromDb.add(new Node(1,0,"张三",50));
        resultFromDb.add(new Node(2,0,"李四",55));
        resultFromDb.add(new Node(3,1,"张三儿子",33));
        resultFromDb.add(new Node(4,3,"张三孙子",10));
        resultFromDb.add(new Node(5,2,"李四女儿",31));
        resultFromDb.add(new Node(6,5,"李四外孙女",11));
        resultFromDb.add(new Node(7,2,"李四儿子",28));
    }

    public static void main(String[] args) {
        List<Node> result = buildTree(0,resultFromDb);
        System.out.println(JSONObject.toJSONString(result));
    }

    private static List<Node> buildTree(int pid, List<Node> list) {
        return list.stream()
                .filter(treeEntity -> treeEntity.getPid().equals(pid))
                .peek(treeEntity -> treeEntity.setChildren(buildTree(treeEntity.getId(),
                        list)))
                .collect(Collectors.toList());
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    private static class Node{
        private Integer id;
        private Integer pid;
        private String name;
        private Integer age;
        private List<Node> children;

        public Node(Integer id, Integer pid, String name, Integer age) {
            this.id = id;
            this.pid = pid;
            this.name = name;
            this.age = age;
        }
    }
}
